/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* SdProjectTaskService
* 项目任务
*
* 修改纪录
* 2021-01-07 版本：1.0 lanjianwei 创建。
* @version 版本：1.0
* @author 作者：lanjianwei
* 创建日期：2021-01-07
*/
package com.topscomm.gpm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.topscomm.base.BaseSystemConst;
import com.topscomm.base.service.impl.BaseChangeLogService;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.gpm.GpmSystemConst;
import com.topscomm.gpm.pojo.*;
import com.topscomm.mis.constant.MisSystemConst;
import com.topscomm.mis.mobile.message.service.SendMessageService;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.gpm.utils.MessageUtil;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.ParameterCache;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.gpm.service.IGpmProjectTaskService;
import com.topscomm.gpm.service.impl.auto.GpmProjectTaskServiceAuto;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.FlowDatacodeCache;
import com.topscomm.tap.common.SessionUserBean;
import org.springframework.transaction.annotation.Transactional;

@Service(value = "gpmProjectTaskService")
@Scope(value = "singleton")
public class GpmProjectTaskService extends GpmProjectTaskServiceAuto implements IGpmProjectTaskService {
    FlowDatacodeCache flowDatacodeCache = new FlowDatacodeCache();
    protected List<Map<String, Object>> flowidList = new ArrayList();
	@Resource(name = "gpmProjectTaskTemplateService")
	private GpmProjectTaskTemplateService gpmProjectTaskTemplateService;
	@Autowired
	private GpmProjectMilepostService gpmProjectMilepostService;
	@Autowired
	private GpmProjectService gpmProjectService;
	@Autowired
	private GpmProjectPlanService gpmProjectPlanService;
	@Autowired
	private DatacodeCache datacodeCache;
	@Autowired
	private BaseChangeLogService baseChangeLogService;
	@Autowired
	private GpmProjectTaskFeedbackService gpmProjectTaskFeedbackService;
	@Autowired
	private ICboMessageAppService cboMessageAppService;
	@Autowired
	private ICboMessageSysService cboMessageSysService;
	@Autowired
	private SendMessageService sendMessageService;
	private static final Logger log= LoggerFactory.getLogger(GpmProjectTaskService.class);
	/**
	 * @author: lanjianwei
	 * @date: 2021-01-07
	 * @param entity
	 * @throws ServiceException
	 * @description:单号生成
	 * @modify:
	 */
	@Override
	protected void beforeInsert(BasicEntity entity){
		super.beforeInsert(entity);
		if (entity.getId() <= 0) {// 赋值Id和单号
			StringBufferProxy sql = new StringBufferProxy();
			long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
			entity.setId(arrayId[0]);
			String docNo = String.valueOf(arrayId[0]);
			docNo = docNo.substring(0, 6) + docNo.substring(9);
			entity.setValue(GpmProjectTaskEntity.FieldDocno, docNo);
			GpmProjectTaskEntity taskEntity = (GpmProjectTaskEntity)entity;
			Date planstartdate = taskEntity.getPlanstartdate();
			Date planenddate = taskEntity.getPlanenddate();
			if(!checkDateRight(planstartdate) || !checkDateRight(planenddate)) {
				throw new ServiceException("日期错误，请填写正确格式的日期！");
			}
			sql.clear();
			sql.appendSingle("operatecode = '{0}'  and  enabled=1",taskEntity.getMilepostcode());
			GpmProjectMilepostEntity gpmProjectMilepostEntity = gpmProjectMilepostService
					.queryObjectByWhere(sql.toString());
			if(gpmProjectMilepostEntity == null) {
				sql.clear();
				sql.appendSingle("operatecode = '{0}'",taskEntity.getMilepostcode());
				gpmProjectMilepostEntity = gpmProjectMilepostService.queryObjectByWhere(sql.toString());
				taskEntity.setMilepostversion(gpmProjectMilepostEntity.getVersion());
			} else {
				taskEntity.setMilepostversion(gpmProjectMilepostEntity.getVersion()+1);
			}
			if(gpmProjectMilepostEntity.getPlanfinishtime() == null) {
				throw new ServiceException("请完善里程碑的计划完成日期！");
			}
			if(planstartdate.compareTo(planenddate)>0){
				throw new ServiceException("任务的计划开始日期不能大于计划完成日期！");
			}
			// 当里程碑的状态为达成，但是新增了任务，此时把里程碑的状态更改为未达成
			if(1== gpmProjectMilepostEntity.getMilepoststate()) {
				gpmProjectMilepostEntity.setMilepoststate(0);
				gpmProjectMilepostEntity.setActualfinishtime(null);
				gpmProjectMilepostService.updateEntity(gpmProjectMilepostEntity);
			}
		}
	}


	/***
	 * @description: 判断日期是否准确
	 * @param date
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/12/2 9:49
	 * @modify:
	 */
	private boolean checkDateRight(Date date) {
        boolean dateIsRight = true;
	    //按照任务模板添加时，任务的计划开始时间和计划完成时间都为空，排除这种情况
	    if(date == null) {
			return dateIsRight;
		}
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    String dateString = simpleDateFormat.format(date);
		try {
			if (date == simpleDateFormat.parse(dateString)) {
                dateIsRight = false;
            }
			return dateIsRight;
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	protected void afterInsert(BasicEntity entity) throws ServiceException {
		super.afterInsert(entity);
		GpmProjectTaskEntity trueEntity = (GpmProjectTaskEntity) entity;
		try {
			Map<String, Object> realMap = this.queryMapById(String.valueOf(trueEntity.getId()));
			GpmProjectPlanEntity planEntity = gpmProjectPlanService.queryObjectByWhere(" projectid = " + trueEntity.getProjectid() + " order by version desc");
			if (planEntity.getVersion()>1) {
				Map<String, Object> changeMap = new HashMap<String, Object>();
				changeMap.put("sourceid", realMap.get("id"));
				changeMap.put("sourcetype", GpmProjectTaskEntity.tableName);
				changeMap.put("newmap", realMap);
				changeMap.put("oldmap", realMap);
				changeMap.put("baselogoperatetype", BaseSystemConst.BaseLogOperateTypeEnum.Add);
				changeMap.put("topsourcetype", GpmProjectPlanEntity.tableName);
				changeMap.put("topsourceid", planEntity.getId());
				baseChangeLogService.insertChangeLog(changeMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("计算完整度或变更记录失败");
		}
	}

	@Override
	protected void updateBefore(Map<String, Object> map) throws ServiceException {
		super.updateBefore(map);
//		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//		StringBufferProxy sql = new StringBufferProxy();
//		sql.appendSingle("operatecode = '{0}'  and  enabled=1",map.get("milepostcode"));
//		List<SdProjectMilepostEntity> sdProjectMilepostEntityList = sdProjectMilepostService
//			.queryByWhere(sql.toString());
//		if(sdProjectMilepostEntityList.size()==0) {
//			sql.clear();
//			sql.appendSingle("operatecode = '{0}'",map.get("milepostcode"));
//			sdProjectMilepostEntityList = sdProjectMilepostService
//				.queryByWhere(sql.toString());
//		}
//		Date planfinishtime = sdProjectMilepostEntityList.get(0).getPlanfinishtime();
//		Date planstartdate=null;
//		Date planenddate =null;
//		try {
//			 planstartdate = simpleDateFormat.parse(map.get("planstartdate").toString());
//			 planenddate = simpleDateFormat.parse(map.get("planenddate").toString());
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//		SimpleDateFormat simple1= new SimpleDateFormat("yyyy-MM-dd 00:00:00");
//		String format = simple1.format(new Date());
//		Date dateNow=null;
//		try {
//			dateNow = simple1.parse(format);
//		} catch (ParseException e) {
//			e.printStackTrace();
//
//		}
//		String sd_taskPlanDate_limit = ParameterCache.getValue("Sd_TaskPlanDate_Limit");
//		if("1".equals(sd_taskPlanDate_limit)){
//			if(planstartdate.compareTo(dateNow)<0){
//				throw new MessageException("任务的计划开始日期不能小于今天！");
//			}
//		}
//		if(planenddate.compareTo(planfinishtime)>0){
//			throw new MessageException("任务的计划完成日期不能大于所属里程碑的计划达成日期！");
//		}
//		if(planstartdate.compareTo(planenddate)>0){
//			throw new MessageException("任务的计划开始日期不能大于计划完成日期！");
//		}

		//更新变更记录
		if ("9".equals(ConvertUtil.convertToString(map.get("state")))) {
			GpmProjectTaskEntity taskEntity = this.queryObjectByWhere(" id = '" + map.get("id") + "'");
			GpmProjectMilepostEntity milepostEntity = gpmProjectMilepostService.queryObjectByWhere(" id = " + taskEntity.getMilepostcode());
			Map<String, Object> oldMap = this.queryMapById(map.get("id").toString());
			Map<String, Object> changeMap = new HashMap<String, Object>();
			changeMap.put("sourceid", map.get("id"));
			changeMap.put("sourcetype", GpmProjectTaskEntity.tableName);
			changeMap.put("newmap", map);
			changeMap.put("oldmap", oldMap);
			changeMap.put("baselogoperatetype", BaseSystemConst.BaseLogOperateTypeEnum.Edit);
			changeMap.put("topsourcetype", GpmProjectPlanEntity.tableName);
			changeMap.put("topsourceid", milepostEntity.getPlanid());
			baseChangeLogService.insertChangeLog(changeMap);
		}

	}
	/**
     * @Title: beforeSubmit
     * @description:
     * @param entity
     * @param sessionUserBean
     * @author: lanjianwei
     * @date: 2021年1月7日下午8:12:55
     * @modify:
    */
    @Override
    protected void beforeSubmit(TapEntity entity, SessionUserBean sessionUserBean) {
        super.beforeSubmit(entity, sessionUserBean);
        GpmProjectTaskEntity gpmProjectTaskEntity = (GpmProjectTaskEntity) entity;
        String deptcode= gpmProjectTaskEntity.getDeptcode();
        gpmProjectTaskEntity.setTaskstate("0");
        gpmProjectTaskEntity.setTaskdistributedate(new Date());
        this.flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_GpmProjectTask",
        		gpmProjectTaskEntity.getApplyusercode(), "sortcode");
        if (flowidList.size() > 0) {// 赋值审批流程id
        	gpmProjectTaskEntity.setFlowid(ConvertUtil.convertToLong(flowidList.get(0).get("id")));
        } else {
            throw new ServiceException("没有匹配的审批流，请联系管理员！");
        }
    }

	/**
	 * @Title: insert
	 * @description:按项目插入任务
	 * @param paraMap
	 * @return
	 * @author: lanjianwei
	 * @date: 2021年1月12日下午5:25:05
	 * @modify:
	*/
	public ResponseResult insertFromProject(Map<String, Object> paraMap) {
		String projectcodeNew=(String)paraMap.get("projectcodenew");
		String projectnameNew=(String)paraMap.get("projectnamenew");
		String ids=(String)paraMap.get("keys");
		List<BasicEntity> insertList = new ArrayList<BasicEntity>();
		if(!StringUtil.isEmpty(ids)) {
			List<GpmProjectTaskEntity>  sdProjectTaskEntities=this.queryByIds(ids);
			for (GpmProjectTaskEntity gpmProjectTaskEntity : sdProjectTaskEntities) {
				gpmProjectTaskEntity = this.insertTaskEntity(gpmProjectTaskEntity,projectcodeNew,projectnameNew);
				insertList.add(gpmProjectTaskEntity);
			}
			if(insertList.size()> 0) {
				this.insertBatch(insertList);
			}
			return ResponseResult.ok("插入任务成功，共 "+ sdProjectTaskEntities.size() +"条。");
		}else {
		   return ResponseResult.ok("没有可插入的任务数据，请确认勾选相关任务！");
		}
	}

	/***
	 * @description: 任务实体赋值
	 * @param gpmProjectTaskEntity
	 * @param projectcodeNew
	 * @param projectnameNew
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/12/2 13:39
	 * @modify:
	 */
	private GpmProjectTaskEntity insertTaskEntity(GpmProjectTaskEntity gpmProjectTaskEntity, String projectcodeNew, String projectnameNew) {
		//赋值任务初始字段
		gpmProjectTaskEntity.setId(0);
		gpmProjectTaskEntity.setTaskstate("0");
		gpmProjectTaskEntity.setState(0);
		gpmProjectTaskEntity.setLatestphase("");
		gpmProjectTaskEntity.setDocno("");
		gpmProjectTaskEntity.setDocdate(new Date());
		gpmProjectTaskEntity.setTaskschedule("0");
		gpmProjectTaskEntity.setMilepostcode("0");
		gpmProjectTaskEntity.setMilepostname("");
		gpmProjectTaskEntity.setProjectcode(projectcodeNew);
		gpmProjectTaskEntity.setProjectname(projectnameNew);
		gpmProjectTaskEntity.setActualstartdate(null);
		gpmProjectTaskEntity.setActualenddate(null);
		gpmProjectTaskEntity.setApplyorgcode(this.getSessionUserBean().getOrg().getCode());
		gpmProjectTaskEntity.setApplydeptcode(this.getSessionUserBean().getDept().getCode());
		gpmProjectTaskEntity.setOrgcode(this.getSessionUserBean().getOrg().getCode());
		gpmProjectTaskEntity.setDeptcode(this.getSessionUserBean().getDept().getCode());
		gpmProjectTaskEntity.setUsercode(this.getSessionUserBean().getUser().getCode());
		gpmProjectTaskEntity.setUsername(this.getSessionUserBean().getUser().getName());
		gpmProjectTaskEntity.setApplyusercode(this.getSessionUserBean().getUser().getCode());
		gpmProjectTaskEntity.setApplyusername(this.getSessionUserBean().getUser().getName());
		return gpmProjectTaskEntity;
	}
	/**
	 * @Title: insertFromTaskTemplate
	 * @description:按模板插入任务
	 * @param paraMap
	 * @return
	 * @author: lanjianwei
	 * @date: 2021年1月14日下午3:55:21
	 * @modify:
	*/
	public ResponseResult insertFromTaskTemplate(Map<String, Object> paraMap) {
		String projectcodeNew=(String)paraMap.get("projectcodenew");
		String projectnameNew=(String)paraMap.get("projectnamenew");
		String ids=(String)paraMap.get("keys");
		List<BasicEntity> insertList = new ArrayList<BasicEntity>();
		if(!StringUtil.isEmpty(ids)) {
			List<GpmProjectTaskTemplateEntity>  sdProjectTaskTemplateEntities=gpmProjectTaskTemplateService.queryByIds(ids);
			for (GpmProjectTaskTemplateEntity gpmProjectTaskTemplateEntity : sdProjectTaskTemplateEntities) {
				GpmProjectTaskEntity gpmProjectTaskEntity =new GpmProjectTaskEntity();
				//赋值任务初始字段
				gpmProjectTaskEntity = this.insertTaskEntity(gpmProjectTaskEntity,projectcodeNew,projectnameNew);
				//赋值拷贝字段
				gpmProjectTaskEntity.setTaskdetail(gpmProjectTaskTemplateEntity.getTaskdetail());
				gpmProjectTaskEntity.setTaskname(gpmProjectTaskTemplateEntity.getTaskname());
				gpmProjectTaskEntity.setTaskpriority(gpmProjectTaskTemplateEntity.getTaskpriority());
				gpmProjectTaskEntity.setTasktype(gpmProjectTaskTemplateEntity.getTasktype());
				insertList.add(gpmProjectTaskEntity);
			}
			if(insertList.size()> 0) {
				this.insertBatch(insertList);
			}
			return ResponseResult.ok("插入任务成功，共 "+ sdProjectTaskTemplateEntities.size() +"条。");
		}else {
			return ResponseResult.ok("没有可插入的任务数据，请确认勾选相关任务！");
		}
	}

	/**
	 * @Title: startTask
	 * @description:开始任务
	 * @param paraMap
	 * @return
	 * @author: lanjianwei
	 * @date: 2021年1月14日下午6:21:38
	 * @modify:
	*/
	public ResponseResult startTask(Map<String, Object> paraMap) {
		String ids=String.valueOf(paraMap.get("ids"));
		if(!StringUtil.isEmpty(ids)) {
			List<GpmProjectTaskEntity>  sdProjectTaskEntities=this.queryByIds(ids);
			List<BasicEntity> updateList = new ArrayList<BasicEntity>();
			for (GpmProjectTaskEntity gpmProjectTaskEntity : sdProjectTaskEntities) {
				gpmProjectTaskEntity.setTaskstate("1");
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
				try {
					String actualstartdate = ConvertUtil.convertToString(paraMap.get("actualstartdate"));
					if(!StringUtil.isEmpty(actualstartdate)) {
						gpmProjectTaskEntity.setActualstartdate(simpleDateFormat.parse(actualstartdate));
					} else {
						gpmProjectTaskEntity.setActualstartdate(new Date());
					}
				} catch (ParseException e) {
					log.error("任务的实际开始时间转换出错:"+e);
					return ResponseResult.error("开始任务失败，请联系管理员");
				}
				updateList.add(gpmProjectTaskEntity);
			}
			if(updateList.size()>0) {
				this.updateBatch(updateList);
			}
			return ResponseResult.ok("成功开始任务");
		}else {
			return ResponseResult.ok("没有可开始的任务，请确认勾选相关任务！");
		}
	}

//	public ResponseResult startTask(Map<String, Object> paraMap) {
//		String ids=String.valueOf(paraMap.get("ids"));
//		if(!StringUtil.isEmpty(ids)) {
//			List<SdProjectTaskEntity>  sdProjectTaskEntities=this.queryByIds(ids);
//			for (SdProjectTaskEntity sdProjectTaskEntity : sdProjectTaskEntities) {
//				sdProjectTaskEntity.setTaskstate("1");
//				sdProjectTaskEntity.setActualstartdate(new Date());
//				this.updateEntity(sdProjectTaskEntity);
//			}
//			return ResponseResult.ok("成功开始任务");
//		}else {
//			return ResponseResult.ok("没有可开始的任务，请确认勾选相关任务！");
//		}
//	}
	/**
	 * @Title: deleteBefore
	 * @description: 任务删除时判断对应的里程碑是否可以变为已达成
	 * @param whereSql
	 * @return
	 * @author: houyuhang
	 * @date: 2021年11月12日
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	protected void deleteBefore(String whereSql) {
		super.deleteBefore(whereSql);
		//找到删除的一条或多条任务
		List<GpmProjectTaskEntity> sdProjectTaskEntities = this.queryByWhere(whereSql);
		List<String> updateListCodes = new ArrayList<String>();
		StringBufferProxy sql = new StringBufferProxy();
		sdProjectTaskEntities.forEach(sdProjectTaskEntity -> {
			sql.clear();
			sql.appendSingle(" milepostcode = '{0}' and id != '{1}' ",sdProjectTaskEntity.getMilepostcode(),sdProjectTaskEntity.getId());
			List<GpmProjectTaskEntity> sdProjectTaskEntitiesExtra = this.queryByWhere(sql.toString());
			if(sdProjectTaskEntitiesExtra.size() > 0) {
				boolean flag = true;
				for(GpmProjectTaskEntity gpmProjectTaskEntity1 : sdProjectTaskEntitiesExtra) {
					// 该里程碑下的其他任务不是完成或关闭状态，里程碑状态不改变
					if(!("2".equals(gpmProjectTaskEntity1.getTaskstate()) || "4".equals(gpmProjectTaskEntity1.getTaskstate()))) {
						flag = false;
						break;
					}
				}
				// 删除这个任务后，其他任务的状态都为已完成或已关闭，这时要将里程碑的状态置为已完成
				if(flag) {
					updateListCodes.add(sdProjectTaskEntity.getMilepostcode());
				}
			}
		});
		if(updateListCodes.size()==0) {
			return;
		}
		String updaCodes = updateListCodes.stream().collect(Collectors.joining("','","'","'"));
		List<BasicEntity> updateList = new ArrayList<>();
		sql.clear();
		sql.appendSingle(" operatecode in ({0})  and milepoststate = '0' and enabled = 1",updaCodes);
		List<GpmProjectMilepostEntity> milepostEntities = gpmProjectMilepostService.queryByWhere(sql.toString());
		for(GpmProjectMilepostEntity milepostEntity:milepostEntities) {
			milepostEntity.setMilepoststate(1);
			milepostEntity.setActualfinishtime(new Date());
			updateList.add(milepostEntity);
		}
		if(updateList.size()>0) {
			gpmProjectMilepostService.updateBatch(updateList);
		}

		//更新变更记录
		List<Map<String,Object>> tasks = this.queryMapByWhere(whereSql);
		Map<String,Object> taskMap = tasks.get(0);
		//变更记录
		if ("9".equals(ConvertUtil.convertToString(taskMap.get("state")))) {
			GpmProjectMilepostEntity milepostEntity = gpmProjectMilepostService.queryObjectByWhere(" id = " + taskMap.get("milepostcode"));
			Map<String,Object> changeMap = new HashMap<String,Object>();
			changeMap.put("sourceid",taskMap.get("id"));
			changeMap.put("sourcetype", GpmProjectTaskEntity.tableName);
			changeMap.put("newmap",taskMap);
			changeMap.put("oldmap",taskMap);
			changeMap.put("baselogoperatetype", BaseSystemConst.BaseLogOperateTypeEnum.Del);
			changeMap.put("topsourcetype", GpmProjectPlanEntity.tableName);
			changeMap.put("topsourceid", milepostEntity.getPlanid());
			baseChangeLogService.insertChangeLog(changeMap);
		}
	}
	/**
	 * @Title: generateTaskcode
	 * @description: 生成任务编号
	 * @param tempList
	 * @return
	 * @author: houyuhang
	 * @date: 2021年11月22日
	 * @modify:
	 */
	public void generateTaskcode(List<Map<String, Object>> tempList) {
		// String str = tempList.stream().map(item -> ConvertUtil.convertToString(item.get("milepostcode"))).distinct().collect(Collectors.joining(","));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" projectcode = '{0}' and enabled = 1 order by planfinishtime asc,id asc ", tempList.get(0).get("projectcode"));
		// 找到该项目enabled=1的所有里程碑，按照里程碑的计划完成日期排序
		List<GpmProjectMilepostEntity> gpmProjectMilepostEntityList = gpmProjectMilepostService.queryByWhere(sql.toString());
		// 任务编号生成
		List<Map<String, Object>> milepostList = new ArrayList<>();
		int count = 1;
		for (GpmProjectMilepostEntity gpmProjectMilepostEntity : gpmProjectMilepostEntityList) {
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("milepostcode", gpmProjectMilepostEntity.getOperatecode());
			dataMap.put("milepostindex", count);
			dataMap.put("taskindex", 1);
			milepostList.add(dataMap);
			count++;
		}
		// 添加generatetaskcode字段表示任务的编号
		tempList.forEach(temp -> {
			milepostList.forEach(milepost -> {
				if (ConvertUtil.convertToString(temp.get("milepostcode")).equals(ConvertUtil.convertToString(milepost.get("milepostcode")))) {
					temp.put("generatetaskcode", ConvertUtil.convertToString(milepost.get("milepostindex")) + '-' + ConvertUtil.convertToString(milepost.get("taskindex")));
					milepost.put("taskindex", ConvertUtil.convertToInt(milepost.get("taskindex")) + 1);
				}
			});
		});
	}
	/**
	 * @Title: queryOverdueTask
	 * @description: 查询任务超期信息
	 * @param paraMap
	 * @return
	 * @author: houyuhang
	 * @date: 2021年12月1日
	 * @modify:
	 */
	@Override
	public Map<String,Object> queryOverdueTask(Map<String, Object> paraMap) {
		Map<String, Object> overdueProjectTaskResult = new HashMap<>();
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" GpmProjectTask.PLANENDDATE<  {0}  and GpmProjectTask.state=9 and " +
						"GpmProjectTask.taskstate in ('{1}','{2}') ",
				SQLAdapter.toDateShort(DateUtil.formatDate(new Date())), GpmSystemConst.TaskStateCode.TaskNotStartCode,
				GpmSystemConst.TaskStateCode.TaskIncompleteCode);
		sql.appendSingle(" and {0} ", gpmProjectService.whereExistsSqlForIndex(GpmProjectTaskEntity.tableName,
				GpmProjectTaskEntity.FieldProjectid, ConvertUtil.convertToString(paraMap.get("dataPermissionFlag"))));
		int countTask = this.getCount(sql.toString());
		overdueProjectTaskResult.put("code", "overdueProjectTaskNum");
		overdueProjectTaskResult.put("name", "超期任务");
		overdueProjectTaskResult.put("iconImg", "/static/images/paojectManager/overdueProjectTask.png");
		overdueProjectTaskResult.put("value", countTask);
		return overdueProjectTaskResult;
	}

	/**
	 * @Title: getProjectInfo
	 * @description: 超期任务获取项目相关信息
	 * @param tempList
	 * @return
	 * @author: zhangjunyao
	 * @date: 2021年12月14日
	 * @modify:
	 */
	@Transactional
	public void getProjectInfo(List<Map<String, Object>> tempList) {
		String projectCodes = tempList.stream().map(map -> ConvertUtil.convertToString(map.get("projectcode")))
				.collect(Collectors.joining("','", "'", "'"));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("projectcode in ({0})", projectCodes);
		List<GpmProjectEntity> projectEntities = gpmProjectService.queryByWhere(sql.toString());
		if (CollectionUtils.isEmpty(projectEntities)) {
			return;
		}
		Map<String, GpmProjectEntity> resultMap = projectEntities.stream().collect(Collectors.toMap(
				GpmProjectEntity::getProjectcode, sdProjectEntity -> sdProjectEntity));
		for (Map<String, Object> mapRow : tempList) {
			String projectCode = ConvertUtil.convertToString(mapRow.get("projectcode"));
			if (resultMap.containsKey(projectCode)) {
				GpmProjectEntity gpmProjectEntity = resultMap.get(projectCode);
				mapRow.put("deptname", gpmProjectEntity.getDeptname());
				String projectlevel = gpmProjectEntity.getProjectlevel();
				mapRow.put("dispprojectlevel", datacodeCache.getValueDynamic("GpmProjectLevel", projectlevel,
						"code", "name"));
				mapRow.put("projectmanager", gpmProjectEntity.getProjectmanager());
			}
		}
	}

	/**
	 * @Title: getProjectInfo
	 * @description:
	 * @param tempList
	 * @return
	 * @author: hdy
	 * @date: 2022年04月07日
	 * @modify:
	 */
	@Override
	public void getTaskFeedbackInfo(List<Map<String, Object>> tempList) {
		StringBufferProxy sql = new StringBufferProxy();
		for (Map<String, Object> mapRow : tempList) {
			String taskid = ConvertUtil.convertToString(mapRow.get("id"));
			sql.clear();
			sql.appendSingle("taskid = '{0}' and state = '1'", taskid);
			List<GpmProjectTaskFeedbackEntity> sdProjectTaskFeedbackEntities = gpmProjectTaskFeedbackService.queryByWhere(sql.toString());
			if(sdProjectTaskFeedbackEntities.size()>0) {
				mapRow.put("feedbackstate", "1");
			}else {
				mapRow.put("feedbackstate", "0");
			}
		}
	}
	/**
	 * @Title: getProjectInfo
	 * @description: 判断里程碑是否全部完成，如果全部完成则将项目状态变更为“复盘阶段”
	 * @param gpmProjectEntity
	 * @return
	 * @author: houyuhang
	 * @date: 2022年04月11日
	 * @modify:
	 */
	public void queryMilepostAllFinished(GpmProjectEntity gpmProjectEntity) {
		// 判断里程碑是否全部完成，如果全部完成则将项目状态变更为“复盘阶段”
		StringBufferProxy whereSql = new StringBufferProxy();
		whereSql.clear();
		whereSql.appendSingle(" projectid = '{0}' and enabled = 1 and state = 9", gpmProjectEntity.getId());
		List<GpmProjectPlanEntity> sdProjectPlanEntities = gpmProjectPlanService.queryByWhere(whereSql.toString());
		if (CollectionUtil.isEmpty(sdProjectPlanEntities)) {
			return;
		}
		// 查询里程碑是否全部完成
		whereSql.clear();
		whereSql.appendSingle(" {0} = '{1}' and enabled = 1 and {2} = {3} ", GpmProjectMilepostEntity.FieldPlanid,
				sdProjectPlanEntities.get(0).getId(), GpmProjectMilepostEntity.FieldMilepoststate, GpmSystemConst.MilepostStateCode.MilepostIncompleteCode);
		List<GpmProjectMilepostEntity> sdProjectMilepostEntities1 = gpmProjectMilepostService.queryByWhere(whereSql.toString());
		if (CollectionUtil.isEmpty(sdProjectMilepostEntities1)) {
			gpmProjectEntity.setProjectstate(GpmSystemConst.SdProjectState.ProjectReview);
			gpmProjectService.updateEntity(gpmProjectEntity);
		}
	}
	/**
	 * @Title:
	 * @description: 策划审批通过后批量下发任务并给任务责任人发送消息提醒
	 * @param
	 * @return
	 * @author: houyuhang
	 * @date: 2022年04月20日
	 * @modify:
	 */
	@Transactional(rollbackFor = Exception.class)
	public String sendMessageToTaskResponsible(String projectCode) {
		// 查询该项目下所有任务
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" {0} = '{1}' and {2} = 0 ", GpmProjectTaskEntity.FieldProjectcode, projectCode, GpmProjectTaskEntity.FieldState);
		List<GpmProjectTaskEntity> sdProjectTaskEntities = this.queryByWhere(sql.toString());
		if (CollectionUtil.isEmpty(sdProjectTaskEntities)) {
			return "";
		}
		// 查询该项目立项信息
		sql.clear();
		sql.appendSingle(" {0} = '{1}' ", GpmProjectEntity.FieldProjectcode, projectCode);
		GpmProjectEntity gpmProjectEntity = gpmProjectService.queryObjectByWhere(sql.toString());
		if (ObjectUtil.isEmpty(gpmProjectEntity)) {
			return "";
		}
		// 配置消息标题内容
		String projectLevel = datacodeCache.getValueDynamic("GpmProjectLevel", gpmProjectEntity.getProjectlevel(), "code", "name");
		String title = "通用项目任务下发提醒";
		StringBufferProxy contentTitle = new StringBufferProxy();
		contentTitle.appendSingle("【{0} {1}级 {2}】", projectCode, projectLevel, gpmProjectEntity.getProjectname());
		String contentBody = "任务已派发给您，请进入“通用项目管理系统”-“任务反馈”查阅任务信息。";
		// 用于封装任务实体，批量更新
		List<BasicEntity> resultList = new ArrayList<>();
		// 用于封装消息，批量插入
		List<Map<String, Object>> appList = new ArrayList<>(), sysList = new ArrayList<>();
		Map<String, Object> appMap = new HashMap<>(), sysMap = new HashMap<>();
		for (GpmProjectTaskEntity gpmProjectTaskEntity : sdProjectTaskEntities) {
			// 更新任务状态
			gpmProjectTaskEntity.setTaskdistributedate(new Date());
			gpmProjectTaskEntity.setSubmitdate(new Date());
			gpmProjectTaskEntity.setState(9);
			gpmProjectTaskEntity.setLatestphase("结束");
			resultList.add(gpmProjectTaskEntity);
			// 获取任务名称，封装消息内容
			StringBufferProxy content = new StringBufferProxy();
			content.appendSingle("{0} “{1}”{2}", contentTitle.toString(), gpmProjectTaskEntity.getTaskname(), contentBody);
			// app推送
			appMap = MessageUtil.createMessageAppMapV1(gpmProjectTaskEntity.getResponsiblecode(), gpmProjectTaskEntity.getResponsible(), title, content.toString(), gpmProjectEntity.getId(),
					GpmProjectTaskEntity.tableName, 0);
			appMap.put("messagetype", MisSystemConst.MobileMessageType.OTHER_TYPE);
			// 系统消息
			sysMap = MessageUtil.createMessageSysMap(gpmProjectTaskEntity.getResponsiblecode(), gpmProjectTaskEntity.getResponsible(), title, content.toString(),
					gpmProjectEntity.getId(), GpmProjectTaskEntity.tableName);
			sysMap.put("messagetype", MisSystemConst.MobileMessageType.OTHER_TYPE);
			// 封装
			appList.add(appMap);
			sysList.add(sysMap);
		}
		// 任务实体批量更新
		this.updateBatch(resultList);
		// 消息批量插入
//		cboMessageAppService.insertList(appList);
//		cboMessageSysService.insertList(sysList);
		sendMessageService.sendAppMessage(appList);
		sendMessageService.sendSysMessage(sysList);
		// 把任务所属里程碑整合为字符串
		String milepostCodes = sdProjectTaskEntities.stream().map(entity -> ConvertUtil.convertToString(entity.getMilepostcode())).distinct()
				.collect(Collectors.joining("','", "'", "'"));
		return milepostCodes;
	}
}
